package udp;


import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * Date:2022/2/18
 * Author:ybc
 * Description:
 */
public class ReceiveTest {

    public static void main(String[] args) throws IOException {
        //创建接收端的Socket对象
        DatagramSocket receiveSocket = new DatagramSocket(12345);
        boolean flag = true;
        while(flag){
            byte[] b = new byte[1024];
            //创建封装数据的数据报包对象
            DatagramPacket packet = new DatagramPacket(b, b.length);
            //接收发送发发送的数据
            receiveSocket.receive(packet);
            //获取发送方的ip地址
            InetAddress inetAddress = packet.getAddress();
            System.out.println("ip:"+inetAddress.getHostAddress());
            //获取发送方发送的数据
            byte[] data = packet.getData();
            System.out.println("发送方发送的数据："+new String(b, 0, packet.getLength()));
        }
        //关闭资源
        receiveSocket.close();
    }

}
